//! # RustCloud 核心模块单元测试
//!
//! 该模块包含了 RustCloud 核心库的全面单元测试，涵盖所有主要功能和边界情况。
//! 测试采用分类组织的方式，确保代码质量和功能正确性。
//!
//! ## 测试分类
//!
//! ### ServiceInstance 测试
//! * 基本创建和验证功能
//! * 元数据操作和管理
//! * 权重设置和验证
//! * 健康状态管理
//! * 序列化和反序列化
//! * 地址解析和格式化
//! * 边界条件和异常情况
//!
//! ### Request/Response 测试
//! * HTTP请求构建和操作
//! * 请求头和查询参数管理
//! * 请求体设置和验证
//! * 响应创建和状态码处理
//! * 序列化功能验证
//!
//! ### 错误处理测试
//! * ValidationError 各种错误场景
//! * ServiceError 错误分类验证
//! * 错误消息和类型匹配
//! * 错误传播和转换
//!
//! ### 综合功能测试
//! * 多组件协作场景
//! * 并发安全性验证
//! * 性能边界测试
//! * 内存安全和资源管理
//!
//! ## 测试策略
//!
//! * **单元测试** - 测试单个函数或方法的功能
//! * **集成测试** - 测试组件间的协作
//! * **边界测试** - 测试极限值和异常输入
//! * **属性测试** - 验证对象属性的正确性
//! * **序列化测试** - 确保数据的持久化和传输正确性
//!
//! ## 运行测试
//!
//! ```bash
//! # 运行所有测试
//! cargo test
//!
//! # 运行特定模块测试
//! cargo test test_service_instance
//!
//! # 运行测试并显示输出
//! cargo test -- --nocapture
//!
//! # 运行测试并生成覆盖率报告
//! cargo test --coverage
//! ```
//!
//! ## 测试数据
//!
//! 测试使用预定义的测试数据和模拟对象，确保测试的可重复性和独立性。
//! 所有测试都是无状态的，不依赖外部资源，可以并行执行。

#[cfg(test)]
mod tests {
    use crate::{*, ValidationError};
    use std::sync::Arc;
    use serde_json;

    // ========================================
    // ServiceInstance 基础功能测试
    // ========================================

    /// 测试 ServiceInstance 的基本创建功能
    /// 
    /// 验证服务实例的基本字段设置和地址生成功能。
    /// 确保创建的实例具有正确的服务标识、网络地址信息。
    #[test]
    fn test_service_instance_creation() {
        let instance = ServiceInstance::new("user-service", "127.0.0.1", 8080, "http");
        assert_eq!(instance.service_id, "user-service");
        assert_eq!(instance.host, "127.0.0.1");
        assert_eq!(instance.port, 8080);
        assert_eq!(instance.scheme, "http");
        assert_eq!(instance.address(), "http://127.0.0.1:8080");
    }

    /// 测试 ServiceInstance 的数据验证功能（正常情况）
    /// 
    /// 验证合法的服务实例配置能够通过验证。
    #[test]
    fn test_service_instance_validation_success() {
        let instance = ServiceInstance::new("test-service", "127.0.0.1", 8080, "http");
        assert!(instance.validate().is_ok());
    }

    /// 测试 ServiceInstance 的数据验证功能（异常情况）
    /// 
    /// 验证各种非法输入能够正确返回相应的验证错误。
    /// 包括空服务ID、无效主机、错误端口、不支持的协议等。
    #[test]
    fn test_service_instance_validation_failures() {
        // Empty service_id
        let mut instance = ServiceInstance::new("", "127.0.0.1", 8080, "http");
        assert!(matches!(instance.validate(), Err(ValidationError::InvalidServiceId(_))));

        // Empty host
        instance = ServiceInstance::new("test", "", 8080, "http");
        assert!(matches!(instance.validate(), Err(ValidationError::InvalidHost(_))));

        // Invalid host
        instance = ServiceInstance::new("test", "not a valid host", 8080, "http");
        assert!(matches!(instance.validate(), Err(ValidationError::InvalidHost(_))));

        // Invalid port (zero)
        instance = ServiceInstance::new("test", "127.0.0.1", 0, "http");
        assert!(matches!(instance.validate(), Err(ValidationError::InvalidPort(_))));

        // Empty scheme
        instance = ServiceInstance::new("test", "127.0.0.1", 8080, "");
        assert!(matches!(instance.validate(), Err(ValidationError::InvalidScheme(_))));

        // Unsupported scheme
        instance = ServiceInstance::new("test", "127.0.0.1", 8080, "ftp");
        assert!(matches!(instance.validate(), Err(ValidationError::InvalidScheme(_))));

        // Invalid weight
        instance = ServiceInstance::new("test", "127.0.0.1", 8080, "http");
        instance.weight = 0.0;
        assert!(matches!(instance.validate(), Err(ValidationError::InvalidWeight(_))));
        instance.weight = -1.0;
        assert!(matches!(instance.validate(), Err(ValidationError::InvalidWeight(_))));
    }

    #[test]
    fn test_service_instance_metadata() {
        let mut instance = ServiceInstance::new("test", "127.0.0.1", 8080, "http");
        instance.add_metadata("version", "1.0.0");
        instance.add_metadata("region", "us-west");
        
        assert_eq!(instance.get_metadata("version"), Some("1.0.0"));
        assert_eq!(instance.get_metadata("region"), Some("us-west"));
        assert_eq!(instance.get_metadata("nonexistent"), None);
    }

    #[test]
    fn test_service_instance_weight_operations() {
        let mut instance = ServiceInstance::new("test", "127.0.0.1", 8080, "http");
        
        // 设置有效权重
        assert!(instance.set_weight(2.5).is_ok());
        assert_eq!(instance.weight, 2.5);
        
        // 设置无效权重
        assert!(instance.set_weight(0.0).is_err());
        assert!(instance.set_weight(-1.0).is_err());
    }

    #[test]
    fn test_service_instance_health_status() {
        let mut instance = ServiceInstance::new("test", "127.0.0.1", 8080, "http");
        assert!(instance.healthy);
        
        instance.set_healthy(false);
        assert!(!instance.healthy);
        
        instance.set_healthy(true);
        assert!(instance.healthy);
    }

    #[test]
    fn test_service_instance_from_address() {
        let instance = ServiceInstance::from_address("test-service", "https://192.168.1.1:9090").unwrap();
        assert_eq!(instance.service_id, "test-service");
        assert_eq!(instance.host, "192.168.1.1");
        assert_eq!(instance.port, 9090);
        assert_eq!(instance.scheme, "https");
    }

    #[test]
    fn test_service_instance_from_address_failures() {
        // Missing scheme
        assert!(matches!(ServiceInstance::from_address("test", "localhost:8080"), Err(ValidationError::InvalidHost(_))));
        // Missing port
        assert!(matches!(ServiceInstance::from_address("test", "http://localhost"), Err(ValidationError::InvalidHost(_))));
        // Invalid port
        assert!(matches!(ServiceInstance::from_address("test", "http://localhost:not-a-port"), Err(ValidationError::InvalidPort(_))));
        // Empty address
        assert!(matches!(ServiceInstance::from_address("test", ""), Err(ValidationError::InvalidHost(_))));
    }

    #[test]
    fn test_service_instance_display() {
        let instance = ServiceInstance::new("user-service", "127.0.0.1", 8080, "http");
        assert_eq!(format!("{}", instance), "user-service@127.0.0.1:8080");
    }

    #[test]
    fn test_service_instance_serialization() {
        let mut instance = ServiceInstance::new("test-service", "127.0.0.1", 8080, "http");
        instance.add_metadata("version", "1.0.0");
        instance.set_weight(2.5).unwrap();
        
        // 测试序列化
        let json = serde_json::to_string(&instance).unwrap();
        assert!(json.contains("test-service"));
        assert!(json.contains("127.0.0.1"));
        
        // 测试反序列化
        let deserialized: ServiceInstance = serde_json::from_str(&json).unwrap();
        assert_eq!(instance, deserialized);
    }

    #[test]
    fn test_service_instance_cluster_operations() {
        let mut instance = ServiceInstance::new("test", "127.0.0.1", 8080, "http");
        assert_eq!(instance.cluster, None);
        
        instance.cluster = Some("main-cluster".to_string());
        assert_eq!(instance.cluster, Some("main-cluster".to_string()));
    }

    #[test]
    fn test_service_instance_advanced_validation() {
        // 测试IPv6地址
        let instance_ipv6 = ServiceInstance::new("test", "::1", 8080, "http");
        assert!(instance_ipv6.validate().is_ok());
        
        // 测试域名
        let instance_domain = ServiceInstance::new("test", "example.com", 8080, "https");
        assert!(instance_domain.validate().is_ok());
        
        // 测试边界端口号
        let instance_min_port = ServiceInstance::new("test", "127.0.0.1", 1, "http");
        assert!(instance_min_port.validate().is_ok());
        
        let instance_max_port = ServiceInstance::new("test", "127.0.0.1", 65535, "https");
        assert!(instance_max_port.validate().is_ok());
        
        // 测试所有支持的协议
        for scheme in ["http", "https", "grpc", "tcp", "udp"] {
            let instance = ServiceInstance::new("test", "127.0.0.1", 8080, scheme);
            assert!(instance.validate().is_ok(), "Scheme {} should be valid", scheme);
        }
    }

    #[test]
    fn test_service_instance_edge_cases() {
        // 测试特殊字符在service_id中
        let instance = ServiceInstance::new("user-service-v2", "127.0.0.1", 8080, "http");
        assert!(instance.validate().is_ok());
        
        // 测试下划线和短横线在host中
        let instance_underscore = ServiceInstance::new("test", "host_name", 8080, "http");
        assert!(instance_underscore.validate().is_ok());
        
        let instance_dash = ServiceInstance::new("test", "host-name.example.com", 8080, "http");
        assert!(instance_dash.validate().is_ok());
        
        // 测试极小权重值
        let mut instance = ServiceInstance::new("test", "127.0.0.1", 8080, "http");
        assert!(instance.set_weight(0.001).is_ok());
        
        // 测试极大权重值
        assert!(instance.set_weight(999999.999).is_ok());
    }

    // Request and Response 测试
    #[test]
    fn test_request_creation_and_operations() {
        let mut request = Request::new("user-service", "POST", "/users");
        assert_eq!(request.service_name, "user-service");
        assert_eq!(request.method, "POST");
        assert_eq!(request.path, "/users");
        
        request.add_header("Content-Type", "application/json");
        request.add_query_param("limit", "10");
        request.set_body(b"{\"name\":\"test\"}".to_vec());
        
        assert_eq!(request.headers.get("Content-Type"), Some(&"application/json".to_string()));
        assert_eq!(request.query_params.get("limit"), Some(&"10".to_string()));
        assert!(request.body.is_some());
    }

    #[test]
    fn test_response_creation_and_operations() {
        let mut response = Response::new(200);
        assert_eq!(response.status, 200);
        assert!(response.is_success());
        
        response.add_header("Content-Type", "application/json");
        response.set_body(b"OK".to_vec());
        
        assert_eq!(response.headers.get("Content-Type"), Some(&"application/json".to_string()));
        assert!(response.body.is_some());
        
        // 测试不同状态码的成功判断
        let response_404 = Response::new(404);
        assert!(!response_404.is_success());
        
        let response_201 = Response::new(201);
        assert!(response_201.is_success());
    }

    #[test]
    fn test_request_and_response_cloning() {
        let mut request = Request::new("user-service", "POST", "/users");
        request.add_header("Content-Type", "application/json");
        request.set_body(b"{}".to_vec());
        
        let cloned_request = request.clone();
        assert_eq!(request.service_name, cloned_request.service_name);
        assert_eq!(request.body, cloned_request.body);

        let mut response = Response::new(200);
        response.set_body(b"OK".to_vec());
        
        let cloned_response = response.clone();
        assert_eq!(response.status, cloned_response.status);
        assert_eq!(response.body, cloned_response.body);
    }

    // ServiceError 测试
    #[test]
    fn test_error_traits() {
        let service_error = ServiceError::ServiceNotFound("test".into());
        assert!(service_error.is_service_not_found());
        assert!(!service_error.is_network_error());
        assert!(!service_error.is_circuit_breaker_open());

        let network_error = ServiceError::NetworkError("timeout".into());
        assert!(network_error.is_network_error());
        assert!(!network_error.is_service_not_found());

        let cb_error = ServiceError::CircuitBreakerOpen("test".into());
        assert!(cb_error.is_circuit_breaker_open());
        assert!(!cb_error.is_network_error());
        
        let timeout_error = ServiceError::TimeoutError("request timeout".into());
        assert!(timeout_error.is_network_error());
    }

    #[test]
    fn test_error_conversions() {
        let io_error = std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "Connection refused");
        let service_error = ServiceError::from(io_error);
        assert!(service_error.is_network_error());
        
        let json_error = serde_json::from_str::<serde_json::Value>("invalid json").unwrap_err();
        let service_error = ServiceError::from(json_error);
        assert!(matches!(service_error, ServiceError::SerializationError(_)));
        
        let validation_error = ValidationError::InvalidServiceId("test".to_string());
        let service_error = ServiceError::from(validation_error);
        assert!(matches!(service_error, ServiceError::ValidationError(_)));
    }

    // 配置结构测试
    #[test]
    fn test_application_config() {
        let mut config = ApplicationConfig::default();
        assert_eq!(config.name, "rustcloud-app");
        assert_eq!(config.port, 8080);
        
        config.metadata.insert("env".to_string(), "test".to_string());
        assert_eq!(config.metadata.get("env"), Some(&"test".to_string()));
    }

    // 以下测试已注释，因为相关配置已移至对应模块
    // RegistryConfig -> rustcloud-registry
    // LoadBalancerConfig -> rustcloud-loadbalancer  
    // CircuitBreakerConfig -> rustcloud-circuit-breaker
    // TransportConfig -> rustcloud-transport

    /*
    #[test]
    fn test_registry_config() {
        let config = RegistryConfig::new(RegistryType::Nacos, "127.0.0.1:8848");
        assert_eq!(config.registry_type, RegistryType::Nacos);
        assert_eq!(config.server_addr, "127.0.0.1:8848");
    }

    #[test]
    fn test_load_balancer_config() {
        let config = LoadBalancerConfig::default();
        assert_eq!(config.strategy, LoadBalancerStrategy::RoundRobin);
        assert!(config.health_check_enabled);
    }

    #[test]
    fn test_circuit_breaker_config() {
        let config = CircuitBreakerConfig::default();
        assert!(config.enabled);
        assert_eq!(config.failure_threshold, 5);
        assert_eq!(config.recovery_timeout, 30000);
        assert_eq!(config.half_open_max_calls, 3);
    }

    #[test]
    fn test_transport_config() {
        let config = TransportConfig::default();
        assert_eq!(config.timeout, 5000);
        assert_eq!(config.retries, 3);
        assert_eq!(config.retry_delay, 1000);
        assert_eq!(config.max_connections, 100);
        assert!(config.keep_alive);
    }
    */

    #[test]
    fn test_health_check_config() {
        use crate::traits::{HealthCheck, HealthCheckType};
        use std::time::Duration;
        
        let config = HealthCheck {
            check_type: HealthCheckType::Http {
                path: "/health".to_string(),
                method: "GET".to_string(),
            },
            endpoint: "http://localhost:8080/health".to_string(),
            interval: Duration::from_secs(30),
            timeout: Duration::from_secs(5),
            failure_threshold: 3,
            success_threshold: 2,
        };
        
        assert_eq!(config.interval, Duration::from_secs(30));
        assert_eq!(config.timeout, Duration::from_secs(5));
        assert_eq!(config.failure_threshold, 3);
        assert_eq!(config.success_threshold, 2);
    }

    #[test]
    fn test_service_info() {
        let info = ServiceInfo::new("user-service", "1.0.0");
        assert_eq!(info.name, "user-service");
        assert_eq!(info.version, "1.0.0");
        assert!(info.group.is_none());
        assert!(info.namespace.is_none());
    }

    #[test]
    fn test_circuit_breaker_state() {
        assert_eq!(CircuitBreakerState::default(), CircuitBreakerState::Closed);
        
        let metrics = CircuitBreakerMetrics::default();
        assert_eq!(metrics.total_calls, 0);
        assert_eq!(metrics.failed_calls, 0);
        assert_eq!(metrics.success_calls, 0);
        assert_eq!(metrics.state, CircuitBreakerState::Closed);
    }

    #[test]
    fn test_load_balancer_strategy_display() {
        assert_eq!(LoadBalancerStrategy::RoundRobin.to_string(), "轮询");
        assert_eq!(LoadBalancerStrategy::Random.to_string(), "随机");
        assert_eq!(LoadBalancerStrategy::WeightedRoundRobin.to_string(), "加权轮询");
        assert_eq!(LoadBalancerStrategy::ConsistentHash.to_string(), "一致性哈希");
    }

    #[test]
    fn test_registry_type_display() {
        assert_eq!(RegistryType::Nacos.to_string(), "Nacos");
        assert_eq!(RegistryType::Consul.to_string(), "Consul");
        assert_eq!(RegistryType::Eureka.to_string(), "Eureka");
    }

    // Mock Registry for Application tests
    struct MockRegistry {
        registered_instances: Arc<std::sync::Mutex<Vec<ServiceInstance>>>,
    }

    impl MockRegistry {
        fn new() -> Self {
            Self {
                registered_instances: Arc::new(std::sync::Mutex::new(Vec::new())),
            }
        }
    }

    #[async_trait::async_trait]
    impl ServiceRegistry for MockRegistry {
        async fn register(&self, instance: ServiceInstance) -> ServiceResult<()> {
            self.registered_instances.lock().unwrap().push(instance);
            Ok(())
        }

        async fn deregister(&self, instance: ServiceInstance) -> ServiceResult<()> {
            let mut instances = self.registered_instances.lock().unwrap();
            instances.retain(|i| i.service_id != instance.service_id || i.host != instance.host || i.port != instance.port);
            Ok(())
        }

        async fn discover(&self, _service_name: &str) -> ServiceResult<Vec<ServiceInstance>> {
            Ok(self.registered_instances.lock().unwrap().clone())
        }

        async fn health_check(&self, service_name: &str) -> ServiceResult<Vec<ServiceInstance>> {
            let instances = self.discover(service_name).await?;
            Ok(instances.into_iter().filter(|i| i.healthy).collect())
        }

        async fn watch(&self, _service_name: &str) -> ServiceResult<Box<dyn ServiceWatcher + Send>> {
            unimplemented!("Mock registry doesn't support watching")
        }
    }

    // Application Framework 测试
    #[test]
    fn test_application_builder() {
        let app = RustCloudApplicationBuilder::new()
            .name("test-service")
            .version("1.0.0")
            .port(8080)
            .host("127.0.0.1")
            .group("default")
            .namespace("public")
            .metadata("env", "test")
            .build();

        let config = app.config();
        assert_eq!(config.name, "test-service");
        assert_eq!(config.version, "1.0.0");
        assert_eq!(config.port, 8080);
        assert_eq!(config.host, Some("127.0.0.1".to_string()));
        assert_eq!(config.group, Some("default".to_string()));
        assert_eq!(config.namespace, Some("public".to_string()));
        assert_eq!(config.metadata.get("env"), Some(&"test".to_string()));
    }

    #[test]
    fn test_service_instance_building() {
        let config = ApplicationConfig {
            name: "test-service".to_string(),
            version: "1.0.0".to_string(),
            port: 8080,
            host: Some("127.0.0.1".to_string()),
            group: Some("test-group".to_string()),
            namespace: Some("test-namespace".to_string()),
            metadata: [("env".to_string(), "test".to_string())].iter().cloned().collect(),
        };

        let app = RustCloudApplication::new(config);
        // Cannot directly test private method, but we can test that the app was created successfully
        assert_eq!(app.config().name, "test-service");
        assert_eq!(app.config().port, 8080);
        assert_eq!(app.config().host, Some("127.0.0.1".to_string()));
    }

    #[tokio::test]
    async fn test_application_startup_without_registry() {
        let config = ApplicationConfig {
            name: "test-service".to_string(),
            version: "1.0.0".to_string(),
            port: 8080,
            host: Some("127.0.0.1".to_string()),
            ..Default::default()
        };

        let app = RustCloudApplication::new(config);
        
        // 测试没有注册中心的应用创建
        assert!(!app.is_started());
        assert_eq!(app.config().name, "test-service");
        assert_eq!(app.config().port, 8080);
    }

    #[tokio::test]
    async fn test_application_with_mock_registry() {
        let config = ApplicationConfig {
            name: "test-service".to_string(),
            version: "1.0.0".to_string(),
            port: 8080,
            host: Some("127.0.0.1".to_string()),
            ..Default::default()
        };

        let mock_registry = Arc::new(MockRegistry::new());
        let app = RustCloudApplication::new(config).with_registry(mock_registry.clone());
        
        // Test application configuration
        assert_eq!(app.config().name, "test-service");
        
        // Test manual registration and deregistration
        let test_instance = ServiceInstance::new("test-service", "127.0.0.1", 8080, "http");
        mock_registry.register(test_instance.clone()).await.unwrap();
        assert_eq!(mock_registry.registered_instances.lock().unwrap().len(), 1);
        
        mock_registry.deregister(test_instance).await.unwrap();
        assert_eq!(mock_registry.registered_instances.lock().unwrap().len(), 0);
    }

    #[test]
    fn test_application_already_started_error() {
        // 由于我们不能实际启动应用（会阻塞），这里只测试状态检查
        let config = ApplicationConfig::default();
        let app = RustCloudApplication::new(config);
        assert!(!app.is_started());
    }

    /*
    #[test]
    fn test_run_config_defaults() {
        let config = RunConfig::default();
        assert!(config.registry.is_none());
        assert_eq!(config.load_balancer.strategy, LoadBalancerStrategy::RoundRobin);
        assert_eq!(config.transport.timeout, 5000);
        assert!(config.circuit_breaker.enabled);
    }
    */

    // ================== 新增综合测试用例 ==================
    
    // ServiceInstance 更全面的测试
    #[test]
    fn test_service_instance_with_group_and_env() {
        let instance = ServiceInstance::with_group_and_env(
            "user-service", "192.168.1.100", 9090, "https",
            Some("user-group".to_string()),
            Some("production".to_string()),
            Some("prod".to_string()),
        );
        
        assert_eq!(instance.service_id, "user-service");
        assert_eq!(instance.host, "192.168.1.100");
        assert_eq!(instance.port, 9090);
        assert_eq!(instance.scheme, "https");
        assert_eq!(instance.group, Some("user-group".to_string()));
        assert_eq!(instance.namespace, Some("production".to_string()));
        assert_eq!(instance.environment, Some("prod".to_string()));
        assert!(instance.healthy);
        assert_eq!(instance.weight, 1.0);
    }
    
    #[test]
    fn test_service_instance_with_weight() {
        let instance = ServiceInstance::new("test", "127.0.0.1", 8080, "http")
            .with_weight(2.5)
            .expect("Weight should be valid");
        assert_eq!(instance.weight, 2.5);
        
        let result = ServiceInstance::new("test", "127.0.0.1", 8080, "http")
            .with_weight(0.0);
        assert!(result.is_err());
        
        let result = ServiceInstance::new("test", "127.0.0.1", 8080, "http")
            .with_weight(-1.5);
        assert!(result.is_err());
    }
    
    #[test]
    fn test_service_instance_environment_methods() {
        let mut instance = ServiceInstance::new("test", "127.0.0.1", 8080, "http");
        
        // Test group operations
        instance.set_group(Some("test-group".to_string()));
        assert_eq!(instance.get_group(), Some("test-group"));
        
        instance.set_group(None);
        assert_eq!(instance.get_group(), None);
        
        // Test namespace operations
        instance.set_namespace(Some("test-namespace".to_string()));
        assert_eq!(instance.get_namespace(), Some("test-namespace"));
        
        instance.set_namespace(None);
        assert_eq!(instance.get_namespace(), None);
        
        // Test environment operations
        instance.set_environment(Some("test-env".to_string()));
        assert_eq!(instance.get_environment(), Some("test-env"));
        
        instance.set_environment(None);
        assert_eq!(instance.get_environment(), None);
        
        // Test cluster operations
        instance.set_cluster(Some("test-cluster".to_string()));
        assert_eq!(instance.get_cluster(), Some("test-cluster"));
        
        instance.set_cluster(None);
        assert_eq!(instance.get_cluster(), None);
    }
    
    #[test]
    fn test_service_instance_host_validation() {
        // Valid IPv4 address
        let instance = ServiceInstance::new("test", "192.168.1.1", 8080, "http");
        assert!(instance.validate().is_ok());
        
        // Valid IPv6 address
        let instance = ServiceInstance::new("test", "::1", 8080, "http");
        assert!(instance.validate().is_ok());
        
        // Valid domain name
        let instance = ServiceInstance::new("test", "example.com", 8080, "http");
        assert!(instance.validate().is_ok());
        
        // Valid domain with subdomain
        let instance = ServiceInstance::new("test", "api.example.com", 8080, "http");
        assert!(instance.validate().is_ok());
        
        // Invalid host with special characters
        let instance = ServiceInstance::new("test", "host@invalid", 8080, "http");
        assert!(instance.validate().is_err());
        
        // Invalid empty host
        let instance = ServiceInstance::new("test", "", 8080, "http");
        assert!(instance.validate().is_err());
    }
    
    #[test]
    fn test_service_instance_scheme_validation() {
        // Test all valid schemes
        let schemes = ["http", "https", "grpc", "tcp", "udp"];
        for scheme in &schemes {
            let instance = ServiceInstance::new("test", "127.0.0.1", 8080, *scheme);
            assert!(instance.validate().is_ok(), "Scheme {} should be valid", scheme);
        }
        
        // Test invalid scheme
        let instance = ServiceInstance::new("test", "127.0.0.1", 8080, "invalid");
        assert!(instance.validate().is_err());
    }
    
    #[test]
    fn test_service_instance_full_service_id() {
        let mut instance = ServiceInstance::new("user-service", "127.0.0.1", 8080, "http");
        
        // No additional info
        assert_eq!(instance.full_service_id(), "user-service");
        
        // With namespace
        instance.set_namespace(Some("production".to_string()));
        assert_eq!(instance.full_service_id(), "ns:production:user-service");
        
        // With group
        instance.set_group(Some("user-group".to_string()));
        assert_eq!(instance.full_service_id(), "ns:production:group:user-group:user-service");
        
        // With environment
        instance.set_environment(Some("prod".to_string()));
        assert_eq!(instance.full_service_id(), "ns:production:group:user-group:env:prod:user-service");
        
        // With cluster
        instance.set_cluster(Some("cluster-1".to_string()));
        assert_eq!(instance.full_service_id(), "ns:production:group:user-group:env:prod:cluster:cluster-1:user-service");
    }
    
    #[test]
    fn test_service_instance_matches_environment() {
        let mut instance = ServiceInstance::new("test", "127.0.0.1", 8080, "http");
        instance.set_namespace(Some("production".to_string()));
        instance.set_group(Some("user-group".to_string()));
        instance.set_environment(Some("prod".to_string()));
        instance.set_cluster(Some("cluster-1".to_string()));
        
        // Empty filter - should match all
        let empty_filter = EnvironmentFilter::new();
        assert!(instance.matches_environment(&empty_filter));
        
        // Matching filter
        let matching_filter = EnvironmentFilter::new()
            .with_namespace("production")
            .with_group("user-group")
            .with_environment("prod")
            .with_cluster("cluster-1");
        assert!(instance.matches_environment(&matching_filter));
        
        // Non-matching namespace
        let non_matching_filter = EnvironmentFilter::new()
            .with_namespace("staging");
        assert!(!instance.matches_environment(&non_matching_filter));
        
        // Non-matching group
        let non_matching_filter = EnvironmentFilter::new()
            .with_namespace("production")
            .with_group("other-group");
        assert!(!instance.matches_environment(&non_matching_filter));
        
        // Partial matching
        let partial_filter = EnvironmentFilter::new()
            .with_namespace("production")
            .with_environment("prod");
        assert!(instance.matches_environment(&partial_filter));
    }
    
    #[test]
    fn test_service_instance_comprehensive_serialization() {
        let mut instance = ServiceInstance::new("user-service", "127.0.0.1", 8080, "http");
        instance.add_metadata("version", "1.0.0");
        instance.set_weight(2.5).unwrap();
        instance.set_healthy(false);
        instance.set_group(Some("user-group".to_string()));
        instance.set_namespace(Some("production".to_string()));
        instance.set_environment(Some("prod".to_string()));
        instance.set_cluster(Some("cluster-1".to_string()));
        
        // Test serialization
        let json = serde_json::to_string(&instance).expect("Serialization should succeed");
        
        // Test deserialization
        let deserialized: ServiceInstance = serde_json::from_str(&json)
            .expect("Deserialization should succeed");
        
        assert_eq!(instance.service_id, deserialized.service_id);
        assert_eq!(instance.host, deserialized.host);
        assert_eq!(instance.port, deserialized.port);
        assert_eq!(instance.scheme, deserialized.scheme);
        assert_eq!(instance.metadata, deserialized.metadata);
        assert_eq!(instance.healthy, deserialized.healthy);
        assert_eq!(instance.weight, deserialized.weight);
        assert_eq!(instance.group, deserialized.group);
        assert_eq!(instance.namespace, deserialized.namespace);
        assert_eq!(instance.environment, deserialized.environment);
        assert_eq!(instance.cluster, deserialized.cluster);
    }
    
    // EnvironmentFilter 测试
    #[test]
    fn test_environment_filter_creation_and_methods() {
        let filter = EnvironmentFilter::new()
            .with_namespace("production")
            .with_group("user-group")
            .with_environment("prod")
            .with_cluster("cluster-1");
            
        assert_eq!(filter.namespace, Some("production".to_string()));
        assert_eq!(filter.group, Some("user-group".to_string()));
        assert_eq!(filter.environment, Some("prod".to_string()));
        assert_eq!(filter.cluster, Some("cluster-1".to_string()));
        assert!(!filter.is_empty());
    }
    
    #[test]
    fn test_environment_filter_is_empty() {
        let empty_filter = EnvironmentFilter::new();
        assert!(empty_filter.is_empty());
        
        let non_empty_filter = EnvironmentFilter::new()
            .with_namespace("test");
        assert!(!non_empty_filter.is_empty());
    }
    
    #[test]
    fn test_environment_filter_serialization() {
        let filter = EnvironmentFilter::new()
            .with_namespace("production")
            .with_environment("prod");
            
        let json = serde_json::to_string(&filter).expect("Serialization should succeed");
        let deserialized: EnvironmentFilter = serde_json::from_str(&json)
            .expect("Deserialization should succeed");
            
        assert_eq!(filter.namespace, deserialized.namespace);
        assert_eq!(filter.group, deserialized.group);
        assert_eq!(filter.environment, deserialized.environment);
        assert_eq!(filter.cluster, deserialized.cluster);
    }
    
    // Request 扩展测试
    #[test]
    fn test_request_extended_operations() {
        let mut request = Request::new("user-service", "POST", "/api/users");
        
        // Test multiple headers
        request.add_header("Content-Type", "application/json");
        request.add_header("Authorization", "Bearer token123");
        request.add_header("X-Request-ID", "req-001");
        
        assert_eq!(request.headers.len(), 3);
        assert_eq!(request.headers.get("Content-Type"), Some(&"application/json".to_string()));
        assert_eq!(request.headers.get("Authorization"), Some(&"Bearer token123".to_string()));
        assert_eq!(request.headers.get("X-Request-ID"), Some(&"req-001".to_string()));
        
        // Test multiple query parameters
        request.add_query_param("limit", "10");
        request.add_query_param("offset", "20");
        request.add_query_param("sort", "name");
        
        assert_eq!(request.query_params.len(), 3);
        assert_eq!(request.query_params.get("limit"), Some(&"10".to_string()));
        assert_eq!(request.query_params.get("offset"), Some(&"20".to_string()));
        assert_eq!(request.query_params.get("sort"), Some(&"name".to_string()));
        
        // Test body setting
        let body = br#"{"name":"John","age":30}"#.to_vec();
        request.set_body(body.clone());
        assert_eq!(request.body, Some(body));
        
        // Test clearing body
        request.set_body(Vec::new());
        assert_eq!(request.body, Some(Vec::new()));
    }
    
    #[test]
    fn test_request_with_empty_path() {
        let request = Request::new("service", "GET", "");
        assert_eq!(request.path, "");
        
        let request = Request::new("service", "GET", "/");
        assert_eq!(request.path, "/");
    }
    
    #[test]
    fn test_request_serialization() {
        let mut request = Request::new("user-service", "POST", "/api/users");
        request.add_header("Content-Type", "application/json");
        request.add_query_param("version", "v1");
        request.set_body(b"{\"test\": true}".to_vec());
        
        let json = serde_json::to_string(&request).expect("Serialization should succeed");
        let deserialized: Request = serde_json::from_str(&json)
            .expect("Deserialization should succeed");
            
        assert_eq!(request.service_name, deserialized.service_name);
        assert_eq!(request.method, deserialized.method);
        assert_eq!(request.path, deserialized.path);
        assert_eq!(request.headers, deserialized.headers);
        assert_eq!(request.query_params, deserialized.query_params);
        assert_eq!(request.body, deserialized.body);
    }
    
    // Response 扩展测试
    #[test]
    fn test_response_status_codes() {
        // Test various successful status codes
        let success_codes = [200, 201, 202, 204, 206];
        for &code in &success_codes {
            let response = Response::new(code);
            assert!(response.is_success(), "Status {} should be success", code);
        }
        
        // Test various error status codes
        let error_codes = [400, 401, 403, 404, 500, 502, 503, 504];
        for &code in &error_codes {
            let response = Response::new(code);
            assert!(!response.is_success(), "Status {} should not be success", code);
        }
    }
    
    #[test]
    fn test_response_extended_operations() {
        let mut response = Response::new(201);
        
        // Test multiple headers
        response.add_header("Content-Type", "application/json");
        response.add_header("Location", "/api/users/123");
        response.add_header("X-Response-Time", "50ms");
        
        assert_eq!(response.headers.len(), 3);
        assert_eq!(response.headers.get("Content-Type"), Some(&"application/json".to_string()));
        assert_eq!(response.headers.get("Location"), Some(&"/api/users/123".to_string()));
        assert_eq!(response.headers.get("X-Response-Time"), Some(&"50ms".to_string()));
        
        // Test body setting
        let body = br#"{"id":123,"name":"John"}"#.to_vec();
        response.set_body(body.clone());
        assert_eq!(response.body, Some(body));
    }
    
    #[test]
    fn test_response_serialization() {
        let mut response = Response::new(200);
        response.add_header("Content-Type", "application/json");
        response.set_body(b"{\"success\": true}".to_vec());
        
        let json = serde_json::to_string(&response).expect("Serialization should succeed");
        let deserialized: Response = serde_json::from_str(&json)
            .expect("Deserialization should succeed");
            
        assert_eq!(response.status, deserialized.status);
        assert_eq!(response.headers, deserialized.headers);
        assert_eq!(response.body, deserialized.body);
    }
    
    // ServiceError 更全面的测试
    #[test]
    fn test_service_error_comprehensive() {
        // Test all error variants
        let service_not_found = ServiceError::ServiceNotFound("test-service".to_string());
        assert!(service_not_found.is_service_not_found());
        assert!(!service_not_found.is_network_error());
        
        let network_error = ServiceError::NetworkError("Connection refused".to_string());
        assert!(network_error.is_network_error());
        assert!(!network_error.is_service_not_found());
        
        let timeout_error = ServiceError::TimeoutError("Request timeout".to_string());
        assert!(timeout_error.is_network_error());
        
        let cb_open = ServiceError::CircuitBreakerOpen("Service unavailable".to_string());
        assert!(cb_open.is_circuit_breaker_open());
        
        let config_error = ServiceError::ConfigurationError("Invalid config".to_string());
        assert!(!config_error.is_network_error());
        
        let serialize_error = ServiceError::SerializationError("JSON parse error".to_string());
        assert!(!serialize_error.is_network_error());
        
        let validation_error = ServiceError::ValidationError(ValidationError::InvalidServiceId("Invalid data".to_string()));
        assert!(!validation_error.is_network_error());
        
        let registry_error = ServiceError::RegistryError("Registry unavailable".to_string());
        assert!(!registry_error.is_network_error());
        
        let load_balancer_error = ServiceError::LoadBalancerError("No available instances".to_string());
        assert!(!load_balancer_error.is_network_error());
        
        let no_instances_error = ServiceError::NoAvailableInstances("Service has no instances".to_string());
        assert!(!no_instances_error.is_network_error());
        
        let metrics_error = ServiceError::MetricsError("Metrics collection failed".to_string());
        assert!(!metrics_error.is_network_error());
        
        let not_implemented = ServiceError::NotImplemented("Feature not implemented".to_string());
        assert!(!not_implemented.is_network_error());
    }
    
    #[test]
    fn test_validation_error_variants() {
        let service_id_error = ValidationError::InvalidServiceId("Empty service ID".to_string());
        let host_error = ValidationError::InvalidHost("Invalid host".to_string());
        let port_error = ValidationError::InvalidPort("Invalid port".to_string());
        let scheme_error = ValidationError::InvalidScheme("Invalid scheme".to_string());
        let weight_error = ValidationError::InvalidWeight("Invalid weight".to_string());
        
        // Test conversion to ServiceError
        let service_error = ServiceError::from(service_id_error);
        assert!(matches!(service_error, ServiceError::ValidationError(_)));
        
        let service_error = ServiceError::from(host_error);
        assert!(matches!(service_error, ServiceError::ValidationError(_)));
        
        let service_error = ServiceError::from(port_error);
        assert!(matches!(service_error, ServiceError::ValidationError(_)));
        
        let service_error = ServiceError::from(scheme_error);
        assert!(matches!(service_error, ServiceError::ValidationError(_)));
        
        let service_error = ServiceError::from(weight_error);
        assert!(matches!(service_error, ServiceError::ValidationError(_)));
    }
    
    // 配置结构更全面的测试
    #[test]
    fn test_service_environment_config() {
        let config = ServiceEnvironmentConfig {
            default_namespace: "production".to_string(),
            default_group: "default".to_string(),
            default_environment: "prod".to_string(),
            default_cluster: "cluster-1".to_string(),
            isolation_enabled: true,
            allow_cross_environment: false,
        };
        
        assert_eq!(config.default_namespace, "production");
        assert_eq!(config.default_group, "default");
        assert_eq!(config.default_environment, "prod");
        assert_eq!(config.default_cluster, "cluster-1");
        assert!(config.isolation_enabled);
        assert!(!config.allow_cross_environment);
    }
    
    #[test]
    fn test_service_environment_config_default() {
        let config = ServiceEnvironmentConfig::default();
        assert_eq!(config.default_namespace, "default");
        assert_eq!(config.default_group, "DEFAULT_GROUP");
        assert_eq!(config.default_environment, "dev");
        assert_eq!(config.default_cluster, "default");
        assert!(config.isolation_enabled);
        assert!(!config.allow_cross_environment);
    }

    // ================ 补充缺失函数的详细测试 ================
    
    // 针对 ServiceInstance::from_address 函数的全面测试
    #[test]
    fn test_service_instance_from_address_comprehensive() {
        // 测试各种有效地址格式
        let valid_addresses = [
            ("http://localhost:8080", "http", "localhost", 8080),
            ("https://example.com:443", "https", "example.com", 443),
            ("grpc://192.168.1.1:9090", "grpc", "192.168.1.1", 9090),
            ("tcp://127.0.0.1:3306", "tcp", "127.0.0.1", 3306),
            ("udp://10.0.0.1:53", "udp", "10.0.0.1", 53),
        ];
        
        for (address, expected_scheme, expected_host, expected_port) in valid_addresses {
            let instance = ServiceInstance::from_address("test-service", address)
                .expect(&format!("Address {} should be valid", address));
            assert_eq!(instance.service_id, "test-service");
            assert_eq!(instance.scheme, expected_scheme);
            assert_eq!(instance.host, expected_host);
            assert_eq!(instance.port, expected_port);
        }
        
        // 测试各种无效地址格式
        let invalid_addresses = [
            "localhost:8080",                    // 缺少协议
            "http://localhost",                  // 缺少端口
            "http://localhost:abc",              // 端口不是数字
            "http://localhost:-1",               // 负端口
            "http://localhost:0",                // 零端口
            "http://localhost:65536",            // 端口过大
            "://localhost:8080",                 // 空协议
            "http://:8080",                      // 空主机
            "http://localhost:8080:extra",       // 格式错误
            "ftp://localhost:8080",              // 不支持的协议
            "",                                  // 空地址
            "http://",                           // 不完整地址
        ];
        
        for address in invalid_addresses {
            let result = ServiceInstance::from_address("test-service", address);
            assert!(result.is_err(), "Address {} should be invalid", address);
        }
    }
    
    // 针对端口边界值的全面测试
    #[test]
    fn test_service_instance_port_boundary_values() {
        // 测试最小有效端口
        let instance_min = ServiceInstance::new("test", "127.0.0.1", 1, "http");
        assert!(instance_min.validate().is_ok());
        
        // 测试最大有效端口
        let instance_max = ServiceInstance::new("test", "127.0.0.1", 65535, "http");
        assert!(instance_max.validate().is_ok());
        
        // 测试常见端口
        let common_ports = [80, 443, 8080, 8443, 3000, 5000, 9000];
        for port in common_ports {
            let instance = ServiceInstance::new("test", "127.0.0.1", port, "http");
            assert!(instance.validate().is_ok(), "Port {} should be valid", port);
        }
        
        // 测试零端口（无效）
        let instance_zero = ServiceInstance::new("test", "127.0.0.1", 0, "http");
        assert!(instance_zero.validate().is_err());
    }
    
    // 针对权重设置的全面测试
    #[test]
    fn test_service_instance_weight_comprehensive() {
        let mut instance = ServiceInstance::new("test", "127.0.0.1", 8080, "http");
        
        // 测试各种有效权重值
        let valid_weights = [0.1, 1.0, 2.5, 5.0, 10.0, 100.0, 999.99];
        for weight in valid_weights {
            assert!(instance.set_weight(weight).is_ok(), "Weight {} should be valid", weight);
            assert_eq!(instance.weight, weight);
        }
        
        // 测试各种无效权重值
        let invalid_weights = [0.0, -0.1, -1.0, -100.0];
        for weight in invalid_weights {
            assert!(instance.set_weight(weight).is_err(), "Weight {} should be invalid", weight);
        }
        
        // 测试 with_weight 方法
        let instance_with_weight = ServiceInstance::new("test", "127.0.0.1", 8080, "http")
            .with_weight(3.5)
            .expect("Weight should be valid");
        assert_eq!(instance_with_weight.weight, 3.5);
        
        // 测试 with_weight 方法的失败情况
        let result = ServiceInstance::new("test", "127.0.0.1", 8080, "http")
            .with_weight(0.0);
        assert!(result.is_err());
    }
    
    // 针对主机地址验证的详细测试
    #[test]
    fn test_service_instance_host_validation_detailed() {
        // IPv4 地址测试
        let ipv4_addresses = [
            "0.0.0.0", "127.0.0.1", "192.168.1.1", "10.0.0.1", 
            "172.16.0.1", "8.8.8.8", "255.255.255.255"
        ];
        for ip in ipv4_addresses {
            let instance = ServiceInstance::new("test", ip, 8080, "http");
            assert!(instance.validate().is_ok(), "IPv4 {} should be valid", ip);
        }
        
        // IPv6 地址测试
        let ipv6_addresses = [
            "::1", "::ffff:192.0.2.1", "2001:db8::1", 
            "fe80::1", "::ffff:0:0", "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
        ];
        for ip in ipv6_addresses {
            let instance = ServiceInstance::new("test", ip, 8080, "http");
            assert!(instance.validate().is_ok(), "IPv6 {} should be valid", ip);
        }
        
        // 域名测试
        let domain_names = [
            "localhost", "example.com", "api.example.com", 
            "sub.domain.example.org", "test-server", "server_name",
            "123-server", "server.local"
        ];
        for domain in domain_names {
            let instance = ServiceInstance::new("test", domain, 8080, "http");
            assert!(instance.validate().is_ok(), "Domain {} should be valid", domain);
        }
        
        // 无效主机地址测试
        let invalid_hosts = [
            "", " ", "host with spaces", "host@invalid", 
            "host#invalid", "host$invalid", "host%invalid",
        ];
        for host in invalid_hosts {
            let instance = ServiceInstance::new("test", host, 8080, "http");
            assert!(instance.validate().is_err(), "Host {} should be invalid", host);
        }
    }
    
    // 针对所有支持协议的测试
    #[test]
    fn test_service_instance_all_supported_schemes() {
        let supported_schemes = ["http", "https", "grpc", "tcp", "udp"];
        
        for scheme in supported_schemes {
            // 测试小写
            let instance = ServiceInstance::new("test", "127.0.0.1", 8080, scheme);
            assert!(instance.validate().is_ok(), "Scheme {} should be valid", scheme);
            
            // 测试地址生成
            let expected_address = format!("{}://127.0.0.1:8080", scheme);
            assert_eq!(instance.address(), expected_address);
        }
        
        // 测试不支持的协议
        let unsupported_schemes = ["ftp", "ssh", "smtp", "imap", "ldap", "file", "ws", "wss"];
        for scheme in unsupported_schemes {
            let instance = ServiceInstance::new("test", "127.0.0.1", 8080, scheme);
            assert!(instance.validate().is_err(), "Scheme {} should be invalid", scheme);
        }
        
        // 测试空协议和特殊字符
        let invalid_schemes = ["", " ", "HTTP", "Http", "http/1.1", "http:", "://"];
        for scheme in invalid_schemes {
            let instance = ServiceInstance::new("test", "127.0.0.1", 8080, scheme);
            assert!(instance.validate().is_err(), "Scheme {} should be invalid", scheme);
        }
    }
    
    // 针对元数据操作的详细测试
    #[test]
    fn test_service_instance_metadata_comprehensive() {
        let mut instance = ServiceInstance::new("test", "127.0.0.1", 8080, "http");
        
        // 测试添加各种类型的元数据
        instance.add_metadata("version", "1.0.0");
        instance.add_metadata("region", "us-west-1");
        instance.add_metadata("zone", "us-west-1a");
        instance.add_metadata("datacenter", "dc-01");
        instance.add_metadata("tags", "web,api,service");
        instance.add_metadata("uptime", "99.9");
        instance.add_metadata("load", "0.5");
        instance.add_metadata("connections", "150");
        
        // 验证所有元数据
        assert_eq!(instance.get_metadata("version"), Some("1.0.0"));
        assert_eq!(instance.get_metadata("region"), Some("us-west-1"));
        assert_eq!(instance.get_metadata("zone"), Some("us-west-1a"));
        assert_eq!(instance.get_metadata("datacenter"), Some("dc-01"));
        assert_eq!(instance.get_metadata("tags"), Some("web,api,service"));
        assert_eq!(instance.get_metadata("uptime"), Some("99.9"));
        assert_eq!(instance.get_metadata("load"), Some("0.5"));
        assert_eq!(instance.get_metadata("connections"), Some("150"));
        
        // 测试不存在的元数据
        assert_eq!(instance.get_metadata("nonexistent"), None);
        assert_eq!(instance.get_metadata(""), None);
        
        // 测试覆盖现有元数据
        instance.add_metadata("version", "1.0.1");
        assert_eq!(instance.get_metadata("version"), Some("1.0.1"));
        
        // 测试空值和特殊字符
        instance.add_metadata("empty", "");
        instance.add_metadata("special", "!@#$%^&*()");
        instance.add_metadata("unicode", "测试数据");
        instance.add_metadata("json", "{\"key\": \"value\"}");
        
        assert_eq!(instance.get_metadata("empty"), Some(""));
        assert_eq!(instance.get_metadata("special"), Some("!@#$%^&*()"));
        assert_eq!(instance.get_metadata("unicode"), Some("测试数据"));
        assert_eq!(instance.get_metadata("json"), Some("{\"key\": \"value\"}"));
    }
    
    // 针对 Request 的全面测试
    #[test]
    fn test_request_comprehensive() {
        // 测试各种HTTP方法
        let http_methods = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"];
        
        for method in http_methods {
            let request = Request::new("test-service", method, "/api/test");
            assert_eq!(request.method, method);
            assert_eq!(request.service_name, "test-service");
            assert_eq!(request.path, "/api/test");
        }
        
        // 测试各种路径格式
        let paths = [
            "/", "/api", "/api/v1/users", "/api/v1/users/123", 
            "/health", "/metrics", "/swagger", "/docs",
            "/api/users?limit=10", "/path/with-dashes", "/path_with_underscores",
            "/api/v2/users/123/orders/456", "", "relative/path"
        ];
        
        for path in paths {
            let request = Request::new("service", "GET", path);
            assert_eq!(request.path, path);
        }
        
        // 测试各种服务名称
        let service_names = [
            "user-service", "order_service", "api-gateway", 
            "service123", "v1-service", "microservice",
            "service", "s", "very-long-service-name-with-dashes"
        ];
        
        for service_name in service_names {
            let request = Request::new(service_name, "GET", "/api");
            assert_eq!(request.service_name, service_name);
        }
        
        // 测试请求头和查询参数
        let mut request = Request::new("service", "POST", "/api/data");
        request.add_header("Content-Type", "application/json");
        request.add_header("Authorization", "Bearer token123");
        request.add_query_param("limit", "10");
        request.add_query_param("offset", "0");
        request.set_body(b"{\"data\": \"test\"}".to_vec());
        
        assert_eq!(request.headers.len(), 2);
        assert_eq!(request.query_params.len(), 2);
        assert!(request.body.is_some());
    }
    
    // 针对 Response 状态码的全面测试
    #[test]
    fn test_response_status_codes_comprehensive() {
        // 2xx 成功响应
        let success_codes = [200, 201, 202, 203, 204, 205, 206, 207, 208, 226];
        for code in success_codes {
            let response = Response::new(code);
            assert_eq!(response.status, code);
            assert!(response.is_success(), "2xx codes should be success");
        }
        
        // 非2xx状态码不应该是成功
        let non_success_codes = [100, 199, 300, 301, 400, 404, 500, 502];
        for code in non_success_codes {
            let response = Response::new(code);
            assert_eq!(response.status, code);
            assert!(!response.is_success(), "Non-2xx codes should not be success");
        }
        
        // 测试响应头和响应体
        let mut response = Response::new(200);
        response.add_header("Content-Type", "application/json");
        response.add_header("Location", "/api/resource/123");
        response.set_body(b"{\"result\": \"success\"}".to_vec());
        
        assert_eq!(response.headers.len(), 2);
        assert!(response.body.is_some());
        assert_eq!(response.headers.get("Content-Type"), Some(&"application/json".to_string()));
    }
    
    // 以下测试已注释，因为相关配置已移至对应模块
    /*
    // 针对各种配置的默认值测试
    #[test]
    fn test_all_config_defaults() {
        // ApplicationConfig 默认值
        let app_config = ApplicationConfig::default();
        assert_eq!(app_config.name, "rustcloud-app");
        assert_eq!(app_config.version, "1.0.0");
        assert_eq!(app_config.port, 8080);
        assert_eq!(app_config.host, Some("0.0.0.0".to_string()));
        assert!(app_config.group.is_none());
        assert!(app_config.namespace.is_none());
        assert!(app_config.metadata.is_empty());
        
        // CircuitBreakerConfig 默认值
        let cb_config = CircuitBreakerConfig::default();
        assert!(cb_config.enabled);
        assert_eq!(cb_config.failure_threshold, 5);
        assert_eq!(cb_config.recovery_timeout, 30000);
        assert_eq!(cb_config.half_open_max_calls, 3);
        
        // TransportConfig 默认值
        let transport_config = TransportConfig::default();
        assert_eq!(transport_config.timeout, 5000);
        assert_eq!(transport_config.retries, 3);
        assert_eq!(transport_config.retry_delay, 1000);
        assert_eq!(transport_config.max_connections, 100);
        assert!(transport_config.keep_alive);
        
        // LoadBalancerConfig 默认值
        let lb_config = LoadBalancerConfig::default();
        assert_eq!(lb_config.strategy, LoadBalancerStrategy::RoundRobin);
        assert!(lb_config.health_check_enabled);
        
        // LoggingConfig 默认值
        let log_config = LoggingConfig::default();
        assert_eq!(log_config.level, "info");
        assert!(matches!(log_config.format, LogFormat::Json));
        assert!(matches!(log_config.output, LogOutput::Console));
        assert!(log_config.file_path.is_none());
        assert!(log_config.console_output);
    }
    */
}